//最顶层的parent 为 -1 ，其余的 parent都是为 上一层节点的id
let arr = [
  { id: 0, name: "1", parent: -1, childNode: [] },
  { id: 1, name: "1", parent: 0, childNode: [] },
  { id: 99, name: "1-1", parent: 1, childNode: [] },
  { id: 111, name: "1-1-1", parent: 99, childNode: [] },
  { id: 66, name: "1-1-2", parent: 99, childNode: [] },
  { id: 1121, name: "1-1-2-1", parent: 112, childNode: [] },
  { id: 12, name: "1-2", parent: 1, childNode: [] },
  { id: 2, name: "2", parent: 0, childNode: [] },
  { id: 21, name: "2-1", parent: 2, childNode: [] },
  { id: 22, name: "2-2", parent: 2, childNode: [] },
  { id: 221, name: "2-2-1", parent: 22, childNode: [] },
  { id: 3, name: "3", parent: 0, childNode: [] },
  { id: 31, name: "3-1", parent: 3, childNode: [] },
  { id: 32, name: "3-2", parent: 3, childNode: [] },
];

function arrToTree(arr, parentId) {
  // 判断是否是顶层节点，如果是就返回。不是的话就判断是不是自己要找的子节点
  const filterArr = arr.filter((item) => {
    return parentId === undefined
      ? item.parent === -1
      : item.parent === parentId;
  });

  // 进行递归调用把子节点加到父节点的 childNode里面去
  filterArr.map((item) => {
    item.childNode = arrToTree(arr, item.id);
    return item;
  });

  return filterArr;
}

arrToTree(arr);

//这道题也是利用递归来进行的，在最开始会进行是否是顶层节点的判断
//如果是就直接返回，如果不是则判断是不是自己要添加到父节点的子节点
//然后再一层一层把节点加入进去
//最后返回这个对象
